package com.rgst.utils;

import java.util.concurrent.TimeUnit;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

/**
 * Created by tancw on 2019/12/24.
 * 缓存工具类
 */
public class CacheUtils {
    public static final int TWO_HOUR = 7200;

    private static Cache<Integer, Cache> cachePool = CacheBuilder.newBuilder()
            .expireAfterAccess(TWO_HOUR, TimeUnit.SECONDS)
            .build();

    public static void set(String key, Object value, Integer expry) {
        Cache cache = getCache(expry);
        cache.put(key, value);
    }

    public static void set(String key, Object value) {
        Cache cache = getCache(TWO_HOUR);
        cache.put(key, value);
    }

    public static Object get(String key) {
        Cache cache = cachePool.getIfPresent(TWO_HOUR);
        if (cache == null) return null;
        return cache.getIfPresent(key);
    }

    public static Object getOrDefault(String key, Object defaultVal) {
        Cache cache = cachePool.getIfPresent(TWO_HOUR);
        if (cache == null) return defaultVal;
        Object value = cache.getIfPresent(key);
        if (value == null) return defaultVal;
        return value;
    }

    public static Object get(String key, Integer expry) {
        Cache cache = cachePool.getIfPresent(expry);
        if (cache == null) return null;
        return cache.getIfPresent(key);
    }

    private static Cache getCache(Integer expry) {
        Cache cache = cachePool.getIfPresent(expry);
        if (cache == null) {
            cache = CacheBuilder.newBuilder()
                    .expireAfterWrite(expry, TimeUnit.SECONDS)
                    .build();
            cachePool.put(expry, cache);
        }
        return cache;
    }
}
